import pcap
import sys
import string
import socket
import struct
import mysqllib
import time,datetime
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import datetime

db = mysqllib.DB()
ips = []
#sql = 'destination_address, source_address, sum(total_len) as sm  from pcap   group by destination_address order by sm desc limit 0,2';
#r = db.select_plain(sql)
#for line in r:
#    ips.append(line[0])
#
#sql = 'destination_address, source_address, sum(total_len) as sm  from pcap   group by source_address order by sm desc limit 0,2';
#r = db.select_plain(sql)
#for line in r:
#    ips.append(line[1])

sql="source_address,destination_address,concat(source_address, ' ', destination_address) as ct, sum(total_len) as st from pcap group by ct order by st desc limit 10"
r = db.select_plain(sql)
for line in r:
    ips.append((line[0],line[1]))

tick = datetime.timedelta(minutes=60)
for ip in ips:
    fp = open('patterns/s'+ip[0]+' '+ip[1],'w')
    ft = open('timescale/s'+ip[0]+' '+ip[1],'w')
    where = " where (source_address = '"+ip[0]+"' and destination_address='"+ip[1]+"')"
    sql = 'min(time),max(time) from pcap ' + where
    r = db.select_plain(sql)
    ctime = r[0][0]
    mtime = r[0][1]
    pdata = []
    while ctime < mtime:
        ft.write(str(ctime)+'\n')
        sql = 'sum(total_len) from pcap '+where+' and (time>\''+str(ctime)+'\' and time<\''+str(ctime+tick)+'\')';
        #print sql
        rt = db.select_plain(sql)
        #entropy = 0
        #count = 0
        #for mt in xrange(1,len(rt)):
        #    entropy += (rt[mt-1][0]-rt[mt][0])**2
        #    count += 1
        #if count:
        #    pdata.append(entropy/count)
        #    print entropy/count
        #else:
        #    pdata.append(0)
        pdata.append(rt[0][0])
        ctime += tick
    for ni in xrange(3,len(pdata)):
        if pdata[ni-1] and pdata[ni]:
            fp.write(str(float(pdata[ni-1] or 0+pdata[ni-2] or 0)/2.0)+','+str(float(pdata[ni-1] or 0+pdata[ni] or 0)/2.0)+'\n')
        plt.bar(ni-1,pdata[ni-1] or 0,1,color = (0,1,0,0.7),edgecolor = (0,1,0,0))
    fp.close()
    ft.close()

    plt.savefig('patterns/s'+ip[0]+' '+ip[1]+'.png')
    plt.clf()
